/**
 * Created by easy on 15/5/11.
 */
/**
 * Created by easy on 15/4/6.
 */
$(document).ready(function () {
    vars.isFirstShow = true;
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var formatDate = function (time) {
        //alert(time)
        if (typeof time != "number") {
            time = parseInt(time)
        }
        //return time;
        //return Date.formatDate(time, "yyyy-MM-dd");
        return mc.dealTime(time, "yyyy-MM-dd");
    };
    var setName = function (name) {
        return name.split(".")[0]
    };
    var getAjaxID = function (string) {
        if (string != undefined) {
            return string.split("#")[1]
        } else {
            return "";
        }
    };
    var getAjaxStatus = function (string) {
        if (string != undefined) {
            return string.split("#")[0]
        } else {
            return "";
        }
    };
    vars.ractiveRemarkList = new Ractive({
        el: "CONTAINER-remark",
        template: "#TEMPLATE-remark",
        data: {
            ractiveData: [],
            formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            },
            setName: setName,
            getAjaxID: getAjaxID,
            getAjaxStatus: getAjaxStatus
        }
    });
    vars.ractiveProcessList = new Ractive({
        el: "CONTAINER-process",
        template: "#TEMPLATE-process",
        data: {
            ractiveData: [],
            formatDate: formatDate,
            setName: setName,
            orderID: vars.orderID,
            getAjaxID: getAjaxID,
            getAjaxStatus: getAjaxStatus,
            quantity: vars.quantity,
            orderID: vars.orderID
        }
    });
    vars.ractiveAbnormalsList = new Ractive({
        el: "CONTAINER-abnormal",
        template: "#TEMPLATE-abnormal",
        data: {
            ractiveData: [],
            formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            },
            getAjaxID: getAjaxID,
            getAjaxStatus: getAjaxStatus,
            setName: setName
        }
    });
    vars.ractiveOrderDetail = new Ractive({
        el: "CONTAINER-detail",
        template: "#TEMPLATE-detail",
        data: {
            ractiveData: {},
            formatDate: formatDate,
            setName: setName
        }
    });
});

(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    vars.queueArray = [];
    basic.deviceReady = function () {
        $(".abnormalCount").hide();
        $(".remarkCount").hide();
        if(!vars.userInfo){
            mc.getUserInfo(function (data) {
                vars.userInfo = JSON.parse(data);
            })
        }
        var params = mc.getParamsFromURL(window.location);
        vars.orderID = params.orderID;
        vars.quantity = params.quantity;
        $("#orderNo").html(params.orderNo);
        /*util.getOrderProcess(function () {
         mc.showContent();
         mc.syncData(["QC_PROCESS"], util.getOrderProcess);
         })*/
        mc.getDataFromLocalStorage("showItem", function (data) {
            vars.currItem = parseInt(data);
            util.showTabByItem(parseInt(data));
        }, "app");
        //订单详情菜单显示未读
        //alert(vars.orderID)
        service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
            if (abnormal.count > 0)
                $(".abnormalCount").text(abnormal.count).show(0);
        });
        service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
            if(count>0)
                $(".remarkCount").text(count).show(0);
        });
        //mc.showContent();
        document.addEventListener('ViewDidAppear', basic.ViewDidAppear, false);
    };
    basic.ViewDidAppear = function () {
        $(".abnormalCount").hide();
        $(".remarkCount").hide();
        if(!vars.userInfo){
            mc.getUserInfo(function (data) {
                vars.userInfo = JSON.parse(data);
            })
        }
        var params = mc.getParamsFromURL(window.location);
        vars.orderID = params.orderID;
        vars.quantity = params.quantity;
        $("#orderNo").html(params.orderNo);
        /*util.getOrderProcess(function () {
         mc.showContent();
         mc.syncData(["QC_PROCESS"], util.getOrderProcess);
         })*/
        mc.getDataFromLocalStorage("showItem", function (data) {
            vars.currItem = parseInt(data);
            util.showTabByItem(parseInt(data));
        }, "app");
        //订单详情菜单显示未读
        //alert(vars.orderID)
        service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
            if (abnormal.count > 0)
                $(".abnormalCount").text(abnormal.count).show(0);
        });
        service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
            if(count>0)
                $(".remarkCount").text(count).show(0);
        });
        $("#orderprocess").hide();
        //location.reload();
    };
    //同步异常表，订单表，备注表，流程表，工厂表数据
    /*util.syncOrderDetailsData = function (callback) {
     mc.syncData(["QC_ORDER", "QC_ABNORMAL", "QC_REMARK", "QC_PROCESS", "QC_PARTY"], callback)
     };*/

    // 选中制定tab
    util.tabtoswitch = function (item, touchObj) {
        vars.currItem = item;
        mc.saveDataToLocalStorage("showItem", item, function () {
        }, "app");
        if ($(touchObj).hasClass("active") == false) {
            $("#btn-addabnormal").hide();
            $("#btn-addremark").hide();
            $(".mc-nodata").hide();
            $(touchObj).addClass("active").siblings(".tab-btn").removeClass("active");
            switch (item) {
                case 1:
                    util.getOrderProcess(function () {
                        mc.syncData(["QC_PROCESS"], util.getOrderProcess);
                    })
                    $(".view-process").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    break;
                case 2:
                    util.getOrderAbnormals(function () {
                        mc.syncData(["QC_ABNORMAL"], util.getOrderAbnormals);
                    })
                    $(".view-abnormal").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    $("#btn-addabnormal").show();
                    break;
                case 3:
                    util.getOrdersRemark(function () {
                        mc.syncData(["QC_REMARK"], util.getOrdersRemark)
                    });
                    //location.reload();
                    $(".view-remark").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    $("#btn-addremark").show();
                    break;
                case 4:
                    util.getOrderDetail(function () {
                        mc.syncData(["QC_ORDER", "QC_PARTY"], util.getOrderDetail);
                    });
                    $(".view-info").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                    break;
            }
        }
    };

    // 显示指定tab
    util.showTabByItem = function (item) {
        $("#btn-addabnormal").hide();
        $("#btn-addremark").hide();
        $(".mc-nodata").hide();
        $($(".tab-btn")[item - 1]).addClass("active");
        switch (item) {
            case 1:
                util.getOrderProcess(function () {
                    mc.syncData(["QC_PROCESS", "QC_ABNORMAL"], util.getOrderProcess);
                })
                $(".view-process").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-process").addClass("active").siblings(".tab-btn").removeClass("active");
                break;
            case 2:
                util.getOrderAbnormals(function () {
                    mc.syncData(["QC_ABNORMAL"], util.getOrderAbnormals);
                })
                $(".view-abnormal").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-abnormal").addClass("active").siblings(".tab-btn").removeClass("active");
                $("#btn-addabnormal").show();
                break;
            case 3:
                util.getOrdersRemark(function () {
                    mc.syncData(["QC_REMARK"], util.getOrdersRemark)
                });
                $(".view-remark").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-remark").addClass("active").siblings(".tab-btn").removeClass("active");
                $("#btn-addremark").show();
                break;
            case 4:
                util.getOrderDetail(function () {
                    mc.syncData(["QC_ORDER", "QC_PARTY"], util.getOrderDetail);
                });
                $(".view-info").removeClass("no-display").siblings(".detail-view").addClass("no-display");
                $(".view-info").addClass("active").siblings(".tab-btn").removeClass("active");
                break;
        }
        mc.showContent();
    };

    util.btnCheck = function (obj, processID, processName) {
        if ($(obj).find("i")[0].className.indexOf("open") < 0) {
            util.changeProcessStatus('T', processID, processName);
            $(obj).find("i").addClass("open");
            $(obj).find("i").removeClass("close");
            $(obj).css("background", "#0093ea");
            $(obj).removeClass("process-btnbgout");
            $(obj).addClass("process-btnbgin");
        } else {
            util.changeProcessStatus('F', processID, processName);
            $(obj).find("i").addClass("close");
            $(obj).find("i").removeClass("open");
            $(obj).css("background", "none");
            $(obj).removeClass("process-btnbgin");
            $(obj).addClass("process-btnbgout");
        }
    }


    util.changeDate = function (touchObj, dateType, processID, processName) {
        vars.processID = processID;
        vars.processName = processName;
        if ($(touchObj).val() != "" ) {
            var date = mc.dealTime($(touchObj).val(), "yyyy-MM-dd");
            $(touchObj).siblings("span").html(date);
            date = new Date(date).getTime();
        }else{
            date = 0;
            $(touchObj).siblings("span").html(dateType)
        }
        util.changeDateSubmit(dateType, date);

    };
    util.changeCompleteQuantity = function (quantity, processID, processName) {
        util.changeQuantitySubmit(quantity, processID, processName);
    };
    util.addProcessRemarkReply = function (remarkID, processName) {
        mc.jump('submit.html?submitType=8&type=3&objID=' + remarkID + '&pID=' + remarkID + '&processName=' + processName, '新增备注回复', 'SubmitModal');
    };
    util.replyRemark = function (parentRemarkID, toUserID, toUserName, processName) {
        if(toUserID){
            mc.jump('submit.html?submitType=8&type=3&objID=' + parentRemarkID + '&processName=' + processName + "&toUserID=" + toUserID + "&toUserName=" + toUserName, '回复 ' + toUserName, 'SubmitModal');
        } else {
            mc.jump('submit.html?submitType=8&type=3&objID=' + parentRemarkID + '&processName=' + processName, '回复异常', 'SubmitModal');
        }
    };
    util.getOrdersRemark = function (callback) {
        var getOrdersRemarkCallback = function (data) {
            //alert(JSON.stringify(data))
            var datas = vars.ractiveRemarkList.data.ractiveData = data;
            vars.ractiveRemarkList.update("ractiveData");
            common.changePhotosProgress();
            common.showPhotos(data);
            var jsonPKStr = "";
            for (var i = 0; i < datas.length; i++) {
                jsonPKStr += ("'"+ datas[i].jsonPK + "'");
                if (i != datas.length - 1) {
                    jsonPKStr += ",";
                }
            }
            service.updateProcessUnreadMark(jsonPKStr, function () {
                service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
                    if(count>0) {
                        $(".remarkCount").text(count).show(0);
                    } else {
                        $(".remarkCount").hide();
                    }
                });
            });
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfRemarkList
            };
            common.morePage(optionsForMorePage);
            if (callback != undefined) {
                callback()
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            orderID: vars.orderID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, getOrdersRemarkCallback);
    };

    // 分页
    util.paginationOfRemarkList = function () {
        var paginationOfRemarkListCallback = function (data) {
            var datas = vars.ractiveRemarkList.data.ractiveData = $.merge(vars.ractiveRemarkList.data.ractiveData, data);
            vars.ractiveRemarkList.update("ractiveData");
            //common.showPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfRemarkList
            };
            common.morePage(optionsForMorePage);
            var jsonPKStr = "";
            for (var i = 0; i < datas.length; i++) {
                jsonPKStr += ("'"+ datas[i].jsonPK + "'");
                if (i != datas.length - 1) {
                    jsonPKStr += ",";
                }
            }
            service.updateProcessUnreadMark(jsonPKStr, function () {})
            common.showPhotos(data);
        };
        var options = {
            orderID: vars.orderID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessRemarkData(options, paginationOfRemarkListCallback)
    };

    util.getOrderProcess = function (callback) {
        var getOrderProcessCallback = function (data) {
            //alert(JSON.stringify(data))
            //alert(data[0].actualTime);
            //console.log(data[0].actualTime)
            //alert(mc.dealTime(parseInt(data[0].actualTime), "yyyy-MM-dd"))
            vars.ractiveProcessList.data.ractiveData = data;
            vars.ractiveProcessList.update("ractiveData");
            if (vars.isFirstShow) {
                vars.isFirstShow = false;
                for (var i = 0; i < data.length; i++) {
                    if (( data[i].status) == "T") {
                        $("#status" + data[i].jsonPK).find("i").addClass("open");
                        $("#status" + data[i].jsonPK).css("background", "#0093ea");
                        $("#status" + data[i].jsonPK).addClass("process-btnbgin");
                    } else {
                        $("#status" + data[i].jsonPK).find("i").removeClass("open").addClass("close");
                        $("#status" + data[i].jsonPK).css("background", "none");
                        $("#status" + data[i].jsonPK).addClass("process-btnend");
                    }
                }
            }
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfProcessList
            };
            common.morePage(optionsForMorePage);
            //util.showPhotos(data);
            if (typeof callback == "function") {
                callback()
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        /* var options = {
         orderID:
         };*/
        service.getOrderProcessData(vars.orderID, getOrderProcessCallback)
    };
    util.paginationOfProcessList = function () {
        var paginationOfProcessListCallback = function (data) {
            vars.ractiveProcessList.data.ractiveData = $.merge(vars.ractiveProcessList.data.ractiveData, data);
            vars.ractiveProcessList.update("ractiveData");
            common.showPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfProcessList
            };
            common.morePage(optionsForMorePage);
        };
        /*var options = {
         orderID: vars.orderID
         };*/
        service.getOrderProcessData(vars.orderID, paginationOfProcessListCallback)
    };

    util.getOrderAbnormals = function (callback) {
        var getOrderAbnormalsCallback = function (data) {
            //console.log(JSON.stringify(data))
            service.getAbnormalRemarkUnreadCountInDetail(vars.orderID, function (orderRemarksData) {
                for (var i in data) {
                    for (var j in orderRemarksData) {
                        if(orderRemarksData[j].jsonPK == data[i].jsonPK) {
                            data[i].abnormalRemarkCount = orderRemarksData[j].count;
                        }
                    }
                }
                vars.ractiveAbnormalsList.data.ractiveData = data;
                vars.ractiveAbnormalsList.update("ractiveData");
            });
            common.changePhotosProgress();
            common.showPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
            //util.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
            /*service.getAbnormalUnreadCount(function(abnormal){
                //alert(JSON.stringify(abnormal))
                for(var i in data ){
                    for(var j in abnormal){
                        if(abnormal[j].jsonPK==data[i].jsonPK){
                            if(abnormal[j].unread=='T'){
                                data[i].abnormalRemarkCount=1
                            }else{
                                data[i].abnormalRemarkCount=0
                            }
                        }
                    }
                }
                service.getAbnormalRemarkUnreadCount(function(remark){
                    for(var i in data){
                        for(var j in remark){
                            if(remark[j].jsonPK==data[i].jsonPK){
                                data[i].abnormalRemarkCount=parseInt(data[i].abnormalRemarkCount)+parseInt(remark[j].count);
                            }
                        }
                    }

                })
            })*/
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            orderID: vars.orderID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessAbnormalsData(options, getOrderAbnormalsCallback)
    };
    util.paginationOfAbnormalsList = function () {
        var paginationOfAbnormalsListCallback = function (data) {
            vars.ractiveAbnormalsList.data.ractiveData = $.merge(vars.ractiveAbnormalsList.data.ractiveData, data);
            vars.ractiveAbnormalsList.update("ractiveData");
            common.changePhotosProgress();
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfAbnormalsList
            };
            common.morePage(optionsForMorePage);
            common.showPhotos(data);
        };
        var options = {
            orderID: vars.orderID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getOrderProcessAbnormalsData(options, paginationOfAbnormalsListCallback)
    };

    // 通过订单号获取流程列表
    util.getProcessByOrderId = function (type) {
        var getProcessByOrderIdCallBack = function (data) {
            //alert(JSON.stringify(data))
            $(".process-listcontainer").empty();
            var submitType = 0;
            var remarkType = 0;
            if (type == "异常") {
                submitType = 1;
                $("#now").html("新增异常");
            } else {
                submitType = 6;
                remarkType = 1;
                $("#now").html("新增备注");
            }
            for (var i = 0; i < data.length; i++) {
                $(".process-listcontainer").append("<div id='submit" + data[i].jsonPK + "'>" + data[i].processName + "</div>");
                $("#submit" + data[i].jsonPK).bind("click", {
                    jsonPK: data[i].jsonPK,
                    processName: data[i].processName
                }, function (even) {
                    mc.jump("submit.html?submitType=" + submitType + "&objID=" + even.data.jsonPK + "&processName=" + even.data.processName + "&orderID=" + vars.orderID + (remarkType == 0 ? "" : "&type=" + remarkType), "添加" + type, "SubmitModal");
                });
            }
            if (data.length == 0) {
                $("#process-nodata").show();
            } else {
                $("#process-nodata").hide()
            }
            $("#orderprocess").show();
        };
        service.getOrderProcessData(vars.orderID, getProcessByOrderIdCallBack);
    };

    util.getOrderDetail = function (callback) {
        var getOrderDetailCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveOrderDetail.data.ractiveData = data[0];
            vars.ractiveOrderDetail.update("ractiveData");
            //alert(JSON.stringify(vars.ractiveOrderDetail.data.ractiveData));
            common.showOrderPhotos(data);
            if (callback != undefined) {
                callback();
            }
        };
        var options = {
            orderID: vars.orderID
        };
        service.getOrderDetailData(options, getOrderDetailCallback)
    };

    // 下拉刷新
    util.pullToRefresh = function () {
        var view = parseInt($(".tab-btn.active").attr("value"));
        switch (view) {
            case 1:
                vars.isFirstShow = true;
                mc.syncData(["QC_ABNORMAL","QC_REMARK","QC_PROCESS"], function () {
                    util.getOrderProcess(pullToRefresh.reset);
                    service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
                        if (abnormal.count > 0) {
                            $(".abnormalCount").text(abnormal.count).show(0);
                        }
                    });
                    service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
                        if(count>0) {
                            $(".remarkCount").text(count).show(0);
                        }
                    });
                });
                break;
            case 2:
                mc.syncData(["QC_REMARK","QC_ABNORMAL"], function () {
                    util.getOrderAbnormals(pullToRefresh.reset);
                    service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
                        if (abnormal.count > 0)
                            $(".abnormalCount").text(abnormal.count).show(0);
                    });
                    service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
                        if(count>0)
                            $(".remarkCount").text(count).show(0);
                    });
                });
                break;
            case 3:
                mc.syncData(["QC_ABNORMAL","QC_REMARK"], function () {
                    util.getOrdersRemark(pullToRefresh.reset);
                    service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
                        if (abnormal.count > 0)
                            $(".abnormalCount").text(abnormal.count).show(0);
                    });
                    service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
                        if(count>0) {
                            $(".remarkCount").text(count).show(0);
                        }
                    });
                });
                break;
            case 4:
                service.getOrderAbnormalRemarkUnreadCount(vars.orderID, function (abnormal) {
                    if (abnormal.count > 0)
                        $(".abnormalCount").text(abnormal.count).show(0);
                });
                service.getOrderPorcessRemarkUnreadCount(vars.orderID, function(count){
                    if(count>0)
                        $(".remarkCount").text(count).show(0);
                });
                pullToRefresh.reset();
                break;
        }
    };
    util.showDetailPhotosByIndex = function (obj, currIndex) {
        common.showOrderPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    }
    vars.inTheSubmit = false;

    // 根据时间类型提交时间
    util.changeDateSubmit = function (dateType, date) {
        var type = "estimatedTime";
        var submitUrl = service.url + "/changeEstimatedTime";
        if (vars.inTheSubmit == false) {

            vars.inTheSubmit = true;
        } else {
            return false
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                util.getOrderProcess();
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "keyID": vars.processID,
            "estimatedTime": date,
            "userID": vars.userInfo.userID
        };
        if (dateType == "实际时间") {
            type = "actualTime";
            requestData = {
                "keyID": vars.processID,
                "actualTime": date,
                "userID": vars.userInfo.userID
            };
            submitUrl = service.url + "/changeActualTime";
        };

        var extraData = {
            "person": vars.userInfo.username,
            "action": "修改了" + vars.processName + "的" + dateType + "为" + mc.dealTime(date, "yyyy-MM-dd"),
            "content": [{"text": ""}]
        };
        //alert(JSON.stringify(requestData))
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateProcess = "UPDATE QC_PROCESS SET " + type + " = '" + date + "'," + type + "Edit = '" + date + "'," + type + "Status = ?, lastModifiedByUserLogin = '" + vars.userInfo.username + "'," +
            "lastUpdateTime='" + time + "' WHERE jsonPK = '" + vars.processID + "';";
        console.log(SQLOfUpdateProcess);
        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeProcessStatus = "UPDATE QC_PROCESS SET " + type + "Status = ? WHERE jsonPK = '" + vars.processID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET processStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.orderID + "';";

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";

        var params = {
            URL: submitUrl,
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: [],
            matchIDs: vars.processID + "," + vars.orderID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateProcess + SQLOfChangeOrderStatus,
                SQLOfAjaxCompleted: SQLOfChangeProcessStatus + SQLOfChangeOrderStatus
            },
            noticePages: ["detail.html", "orders.html", "dynamic.html"]
        };
        mc.submitToAjaxWorker(params, submitCallback)
    }

    util.changeQuantitySubmit = function (quantity, processID, processName) {
        $(".quantity-masklayer" + processID).show();
        if (vars.inTheSubmit == false) {
            vars.inTheSubmit = true;
        } else {
            return false
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                util.getOrderProcess();
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "keyID": processID,
            "completeQuantity": quantity,
            "userID": vars.userInfo.userID
        };
        var extraData = {
            "person": vars.userInfo.username,
            "action": "修改了" + processName + "的完成数为" + quantity + "双",
            "content": [{"text": ""}]
        };
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateProcess = "UPDATE QC_PROCESS SET completeQuantity = " + quantity + ",completeQuantityStatus = ?,completeQuantityEdit = " + quantity + ", lastModifiedByUserLogin = '" + vars.userInfo.username + "'," +
            "lastUpdateTime='" + time + "' WHERE jsonPK = '" + processID + "';";
        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeProcessStatus = "UPDATE QC_PROCESS SET completeQuantityStatus = ? WHERE jsonPK = '" + processID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET processStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.orderID + "';";

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";
        var params = {
            URL: service.url + "/changeProcessQuantity",
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: [],
            matchIDs: processID + "," + vars.orderID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateProcess + SQLOfChangeOrderStatus,
                SQLOfAjaxCompleted: SQLOfChangeProcessStatus + SQLOfChangeOrderStatus
            },
            noticePages: ["detail.html", "orders.html", "dynamic.html"]
        };

        mc.submitToAjaxWorker(params, submitCallback)
    }

    util.changeProcessStatus = function (status, processID, processName) {
        $(".status-masklayer" + processID).show();
        if (vars.inTheSubmit == false) {
            vars.inTheSubmit = true;
        } else {
            return false;
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                setTimeout(function () {
                    util.getOrderProcess();
                }, 200)
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "keyID": processID,
            "userID": vars.userInfo.userID,
            "status": status
            //"actualTime": status == 'T' ? time : null
        };
        var extraData = {
            "person": vars.userInfo.username,
            "action": status == "T" ? "完成了流程：" + processName : "取消了" + processName + "的完成状态",
            "content": [{"text": ""}]
        };
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateProcess = "UPDATE QC_PROCESS SET statusEdit = '" + status + "',status = '" + status + "',statusStatus = ?,actualTimeEdit = '" + (status == 'T' ? time : "1000") + "',actualTime = '" + (status == 'T' ? time : "1000") + "'," +
            "actualTimeStatus = ?, lastModifiedByUserLogin = '" + vars.userInfo.username + "', lastUpdateTime='" + time + "' WHERE jsonPK = '" + processID + "';";

        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeProcessStatus = "UPDATE QC_PROCESS SET statusStatus = ?,actualTimeStatus = ? WHERE jsonPK = '" + processID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET processStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + processID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + processID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.orderID + "';";

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";
        var params = {
            URL: service.url + "/changeProcessStatus",
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: [],
            matchIDs: processID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateProcess + SQLOfChangeOrderStatus,
                SQLOfAjaxCompleted: SQLOfChangeProcessStatus + SQLOfChangeOrderStatus
            },
            noticePages: ["detail.html", "orders.html", "dynamic.html"]
        };

        mc.submitToAjaxWorker(params, submitCallback)
    }

    /*util.showAbnormalPhotosByIndex = function (jsonPK, currIndex) {
     var data = vars.ractiveAbnormalsList.data.ractiveData;
     common.showPhotosByIndex( jsonPK, currIndex);
     }*/
    util.showRemarkPhotosByIndex = function (obj, currIndex) {
        common.showPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    }
    util.showReplyRemarkPhotosByIndex = function (obj, currIndex) {
        common.showReplyPhotosByIndex($(obj).parents(".photos-container").attr("value"), currIndex);
    }
    util.ajaxStarted = function (ajaxID, matchIDs) {
        //alert(vars.currItem + "1")
        if (vars.currItem == 3) {
            var remarkId = "remarkCreate" + ajaxID;
            var remarkObj = document.getElementById(remarkId);
            if (remarkObj) {
                var ajaxItem = $("#remarkCreate" + ajaxID);
                common.changeAjaxBadgeStatus(1, ajaxItem, "abnormalRemark", ajaxID);
            }
        }
        if (vars.currItem == 2) {
            var id = "abnormalCreate" + ajaxID;
            var obj = document.getElementById(id)
            if (obj) {
                var ajaxItem = $("#abnormalCreate" + ajaxID);
                common.changeAjaxBadgeStatus(1, ajaxItem, "abnormal", ajaxID);
            } else {
                util.changeAbnormalStatus(matchIDs);
            }
        }
        if (vars.currItem == 1) {
            util.changeProcessSubmitStatus(matchIDs);
            //alert(1111)
        }
        common.changePhotosProgress()
    };
    util.ajaxCompleted = function (ajaxID, result, matchIDs) {
        //alert(vars.currItem + "2")
        if (vars.currItem == 3) {
            var remarkId = "remarkCreate" + ajaxID;
            var remarkObj = document.getElementById(remarkId);
            if (remarkObj) {
                var ajaxItem = $("#remarkCreate" + ajaxID);
                if (result == "success") {
                    common.changeAjaxBadgeStatus(2, ajaxItem, "orderRemark", ajaxID, mc.syncData(["QC_ABNORMAL"], function () {
                        util.getOrderAbnormals();
                    }));
                } else if (result == "failed") {
                    common.changeAjaxBadgeStatus(3, ajaxItem, "orderRemark", ajaxID);
                }
            }
        }
        if (vars.currItem == 2) {
            var id = "abnormalCreate" + ajaxID;
            var obj = document.getElementById(id)
            if (obj) {
                var ajaxItem = $("#abnormalCreate" + ajaxID);
                if (result == "success") {
                    common.changeAjaxBadgeStatus(2, ajaxItem, "abnormal", ajaxID, util.getAbnormalDetail);
                } else if (result == "failed") {
                    common.changeAjaxBadgeStatus(3, ajaxItem, "abnormal", ajaxID);
                }
            } else {
                util.changeAbnormalStatus(matchIDs);
            }
        }
        if (vars.currItem == 1) {
            util.changeProcessSubmitStatus(matchIDs);
            //alert(222)
        }
        common.changePhotosProgress()
    };
    util.changeAbnormalStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var abnormalID = matchIDsArr[i];
                var abnormalItem = $(document.getElementById(abnormalID));
                if (abnormalItem != undefined) {
                    var findAbnormalStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        var descriptionStatus = data[0].descriptionStatus ? data[0].descriptionStatus.split("#")[0] : "";
                        var abnormalStatusStatus = data[0].abnormalStatusStatus ? data[0].abnormalStatusStatus.split("#")[0] : "";
                        var remarkStatus = data[0].remarkStatus ? data[0].remarkStatus.split("#")[0] : "";
                        var attachmentStatus = data[0].attachmentStatus ? data[0].attachmentStatus.split("#")[0] : "";
                        if (descriptionStatus == "uploading" || abnormalStatusStatus == "uploading" || remarkStatus == "uploading" || attachmentStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, abnormalItem, 'abnormal', abnormalID)
                        } else {
                            if (descriptionStatus == "failed" || abnormalStatusStatus == "failed" || remarkStatus == "failed" || attachmentStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, abnormalItem, 'abnormal', abnormalID)
                            } else {
                                common.changeAjaxBadgeStatus(2, abnormalItem, 'abnormal', abnormalID)
                            }
                        }
                    };
                    var SQLOfFindAbnormalStatus = "SELECT descriptionStatus,abnormalStatusStatus,remarkStatus FROM QC_ABNORMAL WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindAbnormalStatus, [abnormalID], findAbnormalStatusCallback);
                }
            };
            execFindStatus();
        }
    };

    util.changeProcessSubmitStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var processID = matchIDsArr[i];
                var processItem = $("#CONTAINER-process").find("#" + processID)[0];
                if (processItem != undefined) {
                    var findProcessStatusCallback = function (data) {
                        var completeQuantityStatus = data[0].completeQuantityStatus ? data[0].completeQuantityStatus.split("#")[0] : "";
                        var statusStatus = data[0].statusStatus ? data[0].statusStatus.split("#")[0] : "";
                        var remarkStatus = data[0].remarkStatus ? data[0].remarkStatus.split("#")[0] : "";
                        var actualTimeStatus = data[0].actualTimeStatus ? data[0].actualTimeStatus.split("#")[0] : "";
                        var estimatedTimeStatus = data[0].estimatedTimeStatus ? data[0].estimatedTimeStatus.split("#")[0] : "";
                        if (completeQuantityStatus == "uploading" || statusStatus == "uploading" || remarkStatus == "uploading" || actualTimeStatus == "uploading" || estimatedTimeStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, $(processItem), 'process', processID);
                        } else {
                            if (completeQuantityStatus == "failed" || statusStatus == "failed" || remarkStatus == "failed" || actualTimeStatus == "failed" || estimatedTimeStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, $(processItem), 'process', processID)
                            } else {
                                common.changeAjaxBadgeStatus(2, $(processItem), 'process', processID, function () {
                                    $(".status-masklayer" + processID).hide();
                                    $(".quantity-masklayer" + processID).hide();
                                })
                            }
                        }
                    };
                    var SQLOfFindProcessStatus = "SELECT estimatedTimeStatus,completeQuantityStatus,statusStatus,remarkStatus,actualTimeStatus FROM QC_PROCESS WHERE jsonPK = ?;";
                    util.execSQLQueue(SQLOfFindProcessStatus, [processID], findProcessStatusCallback);
                    //mc.execSQL(SQLOfFindProcessStatus, [processID], findProcessStatusCallback);

                }
            };
            execFindStatus();
        }
    };

    var queueArr = new Array();
    util.execSQLQueue = function (sql, params, callback) {
        queueArr.push({"sql": sql, "params": params, "callback": callback});

        if (queueArr.length == 1) {
            mc.execSQL(sql, params, function (data) {
                var obj = queueArr.shift();
                obj.callback(data);
                call();
            });
        }

        function call() {
            if (queueArr.length > 0) {
                var obj = queueArr.shift();
                mc.execSQL(obj.sql, obj.params, function (data) {
                    obj.callback(data);
                    call();
                });
            }
        }
    }

    util.findThisRemarkFailedTask = function (touchObj, remarkID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + remarkID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisRemarkFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisRemarkFailedTaskCallback);
    };

    util.findThisAbnormalFailedTask = function (touchObj, abnormalID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + abnormalID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisAbnormalsFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisAbnormalsFailedTaskCallback);
    };

    util.findThisProcessFailedTask = function (touchObj, processID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + processID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisProcessFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisProcessFailedTaskCallback);
    };
})();